/**
 * Description:
 * File: udp_server.c |Time: 2021-04-12 13:48
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <strings.h>

#define BUF_SIZE 100
#define ERR(msg) do {   \
    perror(msg);        \
    printf("[err]%s:%s:%d\n", __FILE__, __func__, __LINE__); \
    exit(EXIT_FAILURE); \
} while(0)

int main(int argc, char *argv[])
{
    if (argc < 3) {
        printf("Usage: %s <ip> <port>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    char buf[BUF_SIZE] = {0};

    // 填充组播信息结构体并绑定到套接字
    struct sockaddr_in multicastaddr;
    socklen_t addrlen = sizeof(multicastaddr);
    multicastaddr.sin_family = AF_INET;
    multicastaddr.sin_port = htons(atoi(argv[2]));
    multicastaddr.sin_addr.s_addr = inet_addr(argv[1]);
    bind(sockfd, (struct sockaddr *)&multicastaddr, sizeof(multicastaddr));

    // 将本机IP加入多播组
    struct ip_mreqn mreqn;
    mreqn.imr_multiaddr.s_addr = inet_addr(argv[1]);
    mreqn.imr_address.s_addr = htonl(INADDR_ANY);
    mreqn.imr_ifindex = 0;
    if (-1 == setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreqn, sizeof(struct ip_mreq))) {
        ERR("setsockopt");
    }

    while(1) {
        bzero(buf, BUF_SIZE);
        if (-1 == recvfrom(sockfd, buf, BUF_SIZE, 0,
            (struct sockaddr *)&multicastaddr, &addrlen))
        {
            ERR("recvfrom");
        }

        printf("[multicast] %s\n", buf);
    }


    return 0;
}
